<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\Admin\Banner as BannerResource;
use App\Models\Banner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BannersController extends Controller
{
    /**
     * 轮播图列表
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index()
    {
        $banners = Banner::orderByDesc('id')->get();

        return BannerResource::collection($banners);
    }

    /**
     * 创建轮播图
     *
     * @param Request $request
     * @return \App\Http\Resources\Admin\Banner
     */
    public function store(Request $request)
    {
        $count = Banner::count();
        if ($count >= 3) {
            return invalidation('不能上传超过三张轮播图');
        }

        $this->validate($request, [
            'is_display' => 'in:0,1',
            'image_file' => 'required|image',
        ]);

        $path = upload_image('image_file');

        $banner = Banner::create([
            'image'=> $path,
            'is_display'=> $request->post('is_display', 1),
        ]);

        return new BannerResource($banner);
    }

    /**
     * 更新轮播图
     *
     * @param Request $request
     * @param Banner $banner
     */
    public function update(Request $request, Banner $banner)
    {
        $inputs = $this->validate($request, [
            'is_display' => 'in:0,1',
            'image_file' => 'image',
        ]);

        unset($inputs['image_file']);

        if ($request->hasFile('image_file')) {
            $path = upload_image('image_file');

            // 删除旧的轮播图
            Storage::delete($banner->image);
            $banner->image = $path;
        }

        $banner->update($inputs);
    }
}
